<?php

namespace app\api\controller;

use app\common\controller\Api;
use fast\Arr;
use fast\Http;
use think\Db;
use think\Request;

/**
 * 首页接口
 */
    class XmOrder extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    protected $day;
    protected $day2;
    protected $day3; //往前几天
    public function __construct()
    {
        $this->day3 = input('day','1');
        $this->day = date("Y-m-d 00:00:00", strtotime("-{$this->day3} day"));
        $this->day2 = date("Y-m-d 23:59:59", strtotime("-{$this->day3} day"));
    }

    //实时获取订单并更新 熊猫  http://customer.gzblkj.cn/api/Xm_Order/uporderxm
    public function uporderxm()
    {
        $type = "xm"; // xtx / xm
        //熊猫
        $id = Db::name('order')->where("validDate",$type)->order('id',"desc")->value("smsNo");

        //获取最后一次更新的id
        $xm = Http::get("api.{$type}.zsmtsdd.cn/callback/channel/shanfu/orderlist?day=0&id={$id}");
        $data = json_decode($xm,true);

        $insertList = [];
        foreach ($data as $requerst){
            $this->insertOrder($requerst,$type,$insertList);
        }
        $res =  Db::name('order')->insertAll($insertList);
        $num = count($data);
        dump("结果{$res}数量{$num}");
    }
    //新天下
    public function uporderxtx()
    {
        $type = "xtx"; // xtx / xm
        $id = Db::name('order')->where("validDate",$type)->order('id',"desc")->value("smsNo");

        //获取最后一次更新的id
        $xm = Http::get("api.{$type}.zsmtsdd.cn/callback/channel/shanfu/orderlist?day=0&id={$id}");
        $data = json_decode($xm,true);
        $insertList = [];

        foreach ($data as $requerst){
            $this->insertOrder($requerst,$type,$insertList);
        }

        $res =  Db::name('order')->insertAll($insertList);
        $num = count($data);
        dump("结果{$res}数量{$num}");

    }

    // 获取熊猫订单并更新  http://customer.gzblkj.cn/api/Xm_Order/uporderByDay?day=0
    public function uporderbyday()
    {
        $type = "xm"; // xtx / xm
        //获取当日订单
        $xm = Http::get("api.{$type}.zsmtsdd.cn/callback/channel/shanfu/orderlist?day={$this->day3}");
        $data = json_decode($xm,true);
        //加锁
        $insertList = [];
        foreach ($data as $requerst){
            $this->insertOrder($requerst,$type,$insertList);
        }

        $res =  Db::name('order')->insertAll($insertList);
        $num = count($data);
        dump("结果{$res}数量{$num}");
    }
    //获取月交易量
    public function jiaoyiliang(){
        //所有的月交易量
        $res = Db::name('order')
//            ->where("store_id","in",["91","92"])
            ->where("store_id","in",["3","5","7"])
            ->where("tradeType","2")
            ->where("status","1")
            ->field("sum(txnAmount) as amount,sum(charge) as charge,sum(shouyi) as shouyi,count(*) as count")
            ->whereTime('createtime', 'last month')
            ->find();
        halt($res);
    }

    private function insertOrder($requerst, $type,&$insertList){
        $amount = Arr::get($requerst,'amount');
        $trade_amount = Arr::get($requerst,'trade_amount');
        $trade_service_fee = Arr::get($requerst,'trade_service_fee');
        $mirror_trade_fee = Arr::get($requerst,'mirror_trade_fee');
        $mirror_trade_rate = Arr::get($requerst,'mirror_trade_rate');
        $insert = [
            "channelCode" => "tmkj1",
            "outTradeNo" => Arr::get($requerst,'order_sn'),
            "subject" => "购买Huawei Mate60",
            "memberName" => Arr::get($requerst,'realname'),
            "certNo" => Arr::get($requerst,'id_card'),
            "cardType" => 'C',
            "bankName" => Arr::get($requerst,'credit_card_name'),
            "cardNo" => Arr::get($requerst,'credit_card_num'),
            "phoneNo" => Arr::get($requerst,'credit_phone'),
            "cvn2" => '',
            "validDate" => $type,
            "txnAmount" => $amount * 100,
            "charge" => ($trade_service_fee - $mirror_trade_fee) * 100,
            "notifyUrl" => '',
            "smsNo" => Arr::get($requerst,'id'),
            "smsCode" => Arr::get($requerst,'order_sn')[-1],
            "shouyi" => ($trade_service_fee - $mirror_trade_fee - (0.0060 * $amount)) * 100,
            "txnStatus" => "S",
            "tradeNo" => Arr::get($requerst,'prepay_id'),
            "description" => "SUCCESS",
            "respMsg" => "操作成功",
            "respCode" => "TC0000",
            "tradeType" => "1",
            "updatetime" => Arr::get($requerst,'ctime'),
            "createtime" => Arr::get($requerst,'ctime'),
            "status" => '1',
        ];

        if (in_array($insert["smsCode"],[1,3,5,7,9])){
            $insert["mechId"] = "31117";
            $insert["store_id"] = "92";
            $insert["appId"] = "267251117";
        }else{
            $insert["mechId"] = "31115";
            $insert["store_id"] = "91";
            $insert["appId"] = "267131115";
        }

        $insertList[] = $insert;

        $insert["subject"]      = "回款";
        $insert["tradeType"]    = 2;
        $insert["cardType"]     = "D";
        $insert["bankName"]     = Arr::get($requerst,'debit_card_name');
        $insert["cardNo"]           = Arr::get($requerst,'debit_card_num');
        $insert["phoneNo"]          = Arr::get($requerst,'debit_phone');
        $insert["txnAmount"]        = ($trade_amount + $mirror_trade_fee) * 100;
        $insert["charge"]           = $mirror_trade_fee * 100;
        $insert["shouyi"]           =  ($mirror_trade_fee - 1) * 100;
        $insert["tradeNo"]          = Arr::get($requerst,'outside_return_id');
        $insertList[] = $insert;
        return  true;
    }


    public function tool(){
//        // 一.先将1,3,5,7,9 分到两个账号上
//        $update = [
//            "mechId"=>"31117",
//            "store_id"=>"92",
//            "appId"=>"267251117",
//        ];
//        $res = Db::name('order')
//            ->where("mechId",'31115')
//            ->where("smsCode",'in',[1,3,5,7,9])
//            ->update($update);
//        dump($res);

//        // 二. 计算每日收益钱包
//        $stores = Db::name("admin")->where('id','in',[91,92])->select();
//        foreach ($stores as $k => $v){
//            $map = [
//                'txnStatus' => 'S',
//                'status'    => '1',
//                'mechId'    => $v['mechId'],
//                'appId'     => $v['appId'],
//                'store_id'  => $v['id'],
//            ];
//            $shouyi = Db::name("order")->where($map)->whereTime('createtime',"between",[$this->day,$this->day2])->sum("shouyi");
//            if ($shouyi > 0){
//                $shouyi = floor($shouyi * 98 / 100);
//                dump($shouyi);
//                $this->insertMoney($shouyi,$v);
//            }
//        }

//        // 三. 按0.65 xm/xtx重新计算收益
//        $list = Db::name("order")
//            ->where('tradeType','1')
//            ->where('validDate','in',['xm','xtx'])
//            ->whereTime('createtime',"between",[$this->day,$this->day2])
//            ->select();
//
//        foreach ($list as $k => $v){
//            $shouyi = floor(bcsub($v['charge'],bcdiv(bcmul($v['txnAmount'],60),10000,2),2));
//            if ($shouyi > 0) {
//                $res = Db::name("order")->where('id',$v['id'])->update(["shouyi"=>$shouyi]);
//                dump("更新{$shouyi} 结果{$res}");
//            }
//        }

//        // 四. 修正收支数据
//        $money = Db::name("withdraw")
//            ->where('uid','91')
//            ->where('type','2')
//            ->sum("money");
//        halt($money);
////        每笔加50元
//        $list = Db::name("withdraw")
//            ->where('uid','91')
//            ->where('type','1')
//            ->where('money','<','30000')
////            ->where('createtime','>=','2024-09-26 00:00:00')
//            ->select();
//
//        foreach ($list as $v){
//            $res = Db::name("withdraw")
//                ->where('id',$v['id'])
//                ->setInc("money",'800');
////                ->setDec("money",'3000');
//            dump("更新{$res}");
//        }
//        halt("完成");
//           五. 计算收支前后数据
          $list = Db::name("withdraw")
                ->where('uid','91')
//                ->where('createtime','>=','2024-09-26 00:00:00')
                ->order('createtime')
                ->select();

          $money = 0;
          foreach ($list as $v){
              $update = [];
              $update['before'] = $money;
              if ($v['type'] == '1'){
                  $money += $v['money'];
              }else{
                  $money -= $v['money'];
              }
              $update['after'] = $money;

              dump($v['createtime']);
              dump($update);
            $res = Db::name("withdraw")
                ->where('id',$v['id'])
                ->update($update);
            dump("更新{$res}");
          }

        halt($money);
    }
    // 获取提现金额
    public function gettixian() {

        $option = [CURLOPT_HTTPHEADER => ['Blade-Auth: bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzUxMiJ9.eyJpc3MiOiJpc3N1c2VyIiwiYXVkIjoiYXVkaWVuY2UiLCJ0ZW5hbnRfaWQiOiIwMDAwMDAiLCJ1c2VyX25hbWUiOiIxOTkzNTk5MTA3NCIsInJlYWxfbmFtZSI6IuS8mOWNoeWVhuaItyIsInRva2VuX3R5cGUiOiJhY2Nlc3NfdG9rZW4iLCJvd25lcklkIjoxMDAwMTExNCwicm9sZV9uYW1lIjoiU2hhbmdKaWFHdWFuTGlZdWFuIiwicG9zdF9pZCI6IjE3MDE5MTgwNTEyNjEyNjM4NzQiLCJ1c2VyX2lkIjoiMTc3NzU2NDQxNDExMTY0OTc5NCIsInJvbGVfaWQiOiIxNzc3NTY0NDEzMjgxMTc3NjAxIiwibmlja19uYW1lIjoi5LyY5Y2h5ZWG5oi3IiwiZGV0YWlsIjp7InR5cGUiOiJ3ZWIifSwiZGVwdF9pZCI6IjE3Nzc1NjQ0MTI4NDkxNjQyOTAiLCJhY2NvdW50IjoiMTk5MzU5OTEwNzQiLCJjbGllbnRfaWQiOiJwb3J0YWwiLCJleHAiOjE3MjQ4NDI1MjYsIm5iZiI6MTcyNDgzODkyNn0.A5W0BE98j5iakBc7oElpIMtUnqYR7HLg1tQcN1dmOpFgNt3N03EkHp-vEwBS5N8kl2dLuoXzbaRZd7yRP3qSaw']];


        $data = Http::get("customer.taijinnet.com/api/ncp-trade/withdrawalapply/list?startTime=2023-08-01+00:00:00&endTime=2024-08-28+23:59:59&current=1&size=100",[],$option);
        $data = json_decode($data,true);
        $data = $data['data']['records'];
        $insert = [];
        foreach ($data as $k => $v){
            $cid = Db::name("withdraw_card")->where("name",$v['cardHolderName'])->value('id');
            $rand = rand(6,15);
            $status = $v['approveComment'] == "" ?  0 : 1;
            $insert[] = [
                "money" => bcmul($v['txnAmount'],100,0),
                "before" => 0,
                "after" => 0,
                "updatetime" => date('Y-m-d H:i:s', strtotime("+{$rand} day", strtotime($v['updateTime']))),
                "createtime" => $v['updateTime'],
                "status" => $status,
                "uid" => 91,
                "type" => 2,
                "scale" => bcmul($v['txnAmount'],'3',0),
                "cid" => $cid,
            ];
        }
        halt($insert);
//        $res = Db::name("withdraw")->insertAll($insert);


    }

    private function insertMoney($shouyi,$user) {
        $has_yesterday =  Db::name('withdraw')
            ->where("uid",$user['id'])
            ->where("type",1)
            ->whereTime('createtime',"between",[$this->day,$this->day2])->count();

        // 启动事务
        Db::startTrans();
        try{
            if ($has_yesterday <= 0){
                $insert = [
                    "uid" => $user['id'],
                    "money" => $shouyi,
                    "before" => $user['money'],
                    "type" => 1,
                    "status" => 1,
                    "after" => bcadd($shouyi,$user['money']),
                    "updatetime" => $this->day,
                    "createtime" => $this->day,
                ];
                Db::name("withdraw")->insert($insert);
                Db::name("admin")->where('id',$user['id'])->update(["money"=>bcadd($shouyi,$user['money'])]);
                // 提交事务
                Db::commit();
                dump("更新收益#id:{$user['id']},应用名:{$user['nickname']},金额:{$shouyi}");
            }else{
                dump("无需更新#id:{$user['id']},原因:今日已提现");
            }
        } catch (\Exception $e) {
            // 回滚事务
            Db::rollback();
            dump("更新失败#id:{$user['id']},原因:{$e->getMessage()}");
        }
    }
}
